function iq_write_data(file, data, type_)   % -*- octave -*-
handle = fopen(file, "wt");
switch type_
  case "sparse boolean matrix", write_sparse_boolean(handle, data);
  case "sparse float matrix", write_sparse_float(handle, data);
  case "dense float matrix", write_dense_float(handle, data);
  otherwise,
    error("Unknown data type %s", type_);
endswitch;
fclose(handle);
endfunction

function write_sparse_boolean(handle, data)
fprintf(handle, "%s\n", "# IQ sparse boolean matrix format 0.1");
write_rows_cols(handle, data);
for i=1:size(data,1)
  fprintf(handle, "%d ", find(data(i,:))-1);
  fprintf(handle, "\n");
endfor
endfunction 

function write_sparse_float(handle, data)
fprintf(handle, "%s\n", "# IQ sparse real matrix format 0.1");
write_rows_cols(handle, data);
for i=1:size(data,1)
  [dummy where what] = find(data(i,:));
  fprintf(handle, "%d:%f ", [where-1; what](:));
  fprintf(handle, "\n");
endfor
endfunction

function write_dense_float(handle, data)
fprintf(handle, "%s\n", "# IQ dense real matrix format 0.1");
write_rows_cols(handle, data);
for i=1:size(data,1)
  fprintf(handle, "%f ", data(i,:));
  fprintf(handle, "\n");
endfor
endfunction

function write_rows_cols(handle, data)
[r c] = size(data);
fprintf(handle, "# rows: %d\n", r);
fprintf(handle, "# columns: %d\n", c);
endfunction
